package com.kklldog.logindemo;

import com.kklldog.core.task.BaseAsyncTask;
import com.kklldog.core.task.TaskListener;
import com.kklldog.core.task.TaskParams;
import com.kklldog.core.task.TaskResult;
import com.kklldog.tasks.UserOperationTask;
import com.kklldog.po.User;
import com.kklldog.util.Dialog;
import com.mobsandgeeks.saripaar.Rule;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.Validator.ValidationListener;
import com.mobsandgeeks.saripaar.annotation.Required;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/** 
 * @author mj.zhou 
 * @version create：2013-12-1 下午4:03:48 
 * Login
 */
public class LoginActivity extends Activity   {

	@Required(order = 1, message="用户名不能为空")
	private EditText tbxUser=null;
	@Required(order = 2,message="密码不能为空")
	private EditText tbxPsw =null;
	
	private Validator validator;
	private ProgressDialog pd;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		//初始化监听
		initListener();
		//实例化校验类库
		validator = new Validator(this);
		validator.setValidationListener(validationListener);
	}

	/**
	 * 初始化监听
	 */
	private void initListener() {
		
		Button btn = (Button)this.findViewById(R.id.btnLogin);
		tbxUser=(EditText)this.findViewById(R.id.txtUser);
	    tbxPsw=(EditText)this.findViewById(R.id.txtPassword);
		
		btn.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				validator.validate();
			}


		});
	}
	private void login() {
		try {
			UserOperationTask task = new UserOperationTask();//异步登陆
			task.setListener(loginTaskListener);//设置监听
			TaskParams param = new TaskParams();//实例化传参类
			param.setExecMethodName(UserOperationTask.EXCUTE_LOGIN);//设置要执行的内部方法
			param.put("userName", tbxUser.getText().toString());//设置参数
			param.put("password", tbxPsw.getText().toString());
			task.execute(param);//调用异步方法
		} catch (Exception e) {
			pd.cancel();
			Dialog.showAlert("异常", e.getMessage(),this);	
		}
	};
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}


    /**
     * Task监听
     */
	private TaskListener loginTaskListener =new TaskListener(){

		@Override
		public void onPreExecute(BaseAsyncTask task) {
			// TODO Auto-generated method stub
			pd = ProgressDialog.show(LoginActivity.this,"", "正在登录......", true);
		}

		@Override
		public void onPostExecute(BaseAsyncTask task, TaskResult<?> result) {
			// TODO Auto-generated method stub
			pd.cancel();
			if(result.getIsSuccess())
			{ 
				if(result.getCompleteMethodName().equals("excuteLogin"))
				{
					User user = (User)result.getData();
					if(user!=null){
					
						//go to user list
						Intent intent = new Intent();  
				        intent.setClass(LoginActivity.this,UserActivity.class);  
				        startActivity(intent);  
				        finish();
					}
				}
				
			}
			else{
				Dialog.showToast(result.getErrorMessage(), LoginActivity.this);
			}
			
		}

		@Override
		public void onCancelled(BaseAsyncTask task) {
			// TODO Auto-generated method stub
			
		}
		
	};

	/**
	 * 验证监听
	 */
	private ValidationListener validationListener=new ValidationListener()
	{
		@Override
		public void preValidation() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess() {
			// TODO Auto-generated method stub
			login();
		}

		@Override
		public void onFailure(View failedView, Rule<?> failedRule) {
			// TODO Auto-generated method stub
			String message = failedRule.getFailureMessage();

	        if (failedView instanceof EditText) {
	            failedView.requestFocus();
	            ((EditText) failedView).setError(message);
	        } else {
	            Dialog.showToast(message,LoginActivity.this);
	        }
		}

		@Override
		public void onValidationCancelled() {
			// TODO Auto-generated method stub
			
		}
	};
}
